import time

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from web.forms import project
from web import models
from utils.cos import create_bucket


def project_list(request):
    if request.method == 'GET':
        form = project.ProjectModelForm(request)
        project_dict = {'star': [], 'my': [], 'join': []}
        for row in models.Project.objects.filter(creator=request.tracer.user):
            if row.star:
                project_dict['star'].append({'value': row, 'type': 'my'})
            else:
                project_dict['my'].append({'value': row, 'type': 'my'})

        for item in models.ProjectUser.objects.filter(user=request.tracer.user):
            if item.star:
                project_dict['star'].append({'value': item.project, 'type': 'join'})
            else:
                project_dict['join'].append({'value': item.project, 'type': 'join'})

        return render(request, 'project_list.html', {'form': form, 'project_dict': project_dict})

    form = project.ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        bucket_name = f'{request.tracer.user.mobile_phone}-{str(int(time.time()) * 1000)}-1325738692'
        region = 'ap-shanghai'
        create_bucket(bucket_name, region)
        form.instance.bucket = bucket_name
        form.instance.region = region
        form.instance.creator = request.tracer.user
        instance = form.save()
        models.IssuesType.objects.bulk_create(
            [models.IssuesType(project=instance, title=item) for item in models.IssuesType.PROJECT_INIT_LIST])
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')
    return HttpResponse('请求错误')


def project_un_star(request, project_type, project_id):
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    if project_type == 'join':
        models.ProjectUser.objects.filter(id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')
    return HttpResponse('请求错误')
